package com.rede.didiok.user.modulelist.rank.exception;

import java.util.HashMap;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.rede.didiok.common.enums.BizCodeEnum;
import com.rede.didiok.common.utils.R;


/**
 * @Author: liuss
 * @DateTime: 2023-07-14 19:45
 * @Description:
 */
//@ControllerAdvice
//@ResponseBody
@Slf4j
@RestControllerAdvice(basePackages = "com.rede.didiok.user.modulelist.rank.controller")
public class ExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验异常：{}，异常类型：{}",e.getMessage(), e.getClass());
        Map<String,String> map = new HashMap<>(8);
        BindingResult result = e.getBindingResult();
        result.getFieldErrors().forEach(fieldError -> {
            map.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(),BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data", map);
    }

    @ExceptionHandler(value = Exception.class)
    public R handleException(Throwable e){
        log.error("错误：",e);
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }
}
